package cn.edu.ctbu.websql.service;

import cn.edu.ctbu.websql.domain.Teacher;
import cn.edu.ctbu.websql.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherService {
    @Autowired
    private TeacherRepository teacherRepository;

    /**
     * 查询全部教师信息
     * @return
     */
    public List<Teacher> findAll(){
        return teacherRepository.findAll();
    }
    /**
     * 按照 id 查询
     * @param id 主键，参数
     * @return
     */
    public Teacher findById(Integer id){
        return teacherRepository.findById(id).orElse(null);
    }

    /**
     * 按照姓查询
     * @param name 参数
     * @return
     */
    public List<Teacher> findByName(String name){
        return teacherRepository.findByNameLike(name);
    }

    /**
     * 插入教师数据
     * @param teacher 参数
     */
    public void Insert(Teacher teacher){
        teacherRepository.save(teacher);
    }

    /**
     * 更新数据
     * @param teacher
     */
    public void upDate(Teacher teacher){
        teacherRepository.save(teacher);
    }

    /**
     * 删除数据
     * @param id
     */
    public void delete(Integer id){
        teacherRepository.deleteById(id);
    }

    /**
     * 模糊查询like工号前四位
     * @return
     */
    public List<Teacher> getLatestAdmissionTeachers() {
        // 获取工号最大的教师
        Teacher latestTeacher = teacherRepository.findTopByOrderByNoDesc();

        if (latestTeacher != null) {
            // 提取工号的前四位作为入职时间
            String no = latestTeacher.getNo().substring(0, 4);

            // 根据入职时间进行模糊查询
            return teacherRepository.findByNoLike(no + "%");
        }

        return List.of(); // 返回空列表
    }
}
